package stuServlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class DoDownLoadServlet extends HttpServlet {

	public DoDownLoadServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.execute(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.execute(request, response);

	}
	public void execute(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String []url=request.getParameterValues("one");
		for(int i=0;i<url.length;i++){
			File file=new File(url[i]);
			if(file.exists()){

				response.setHeader( "Content-Disposition","attachment; filename="+new String(file.getName().getBytes("gb2312"),"iso-8859-1") ); 
				response.setContentType("application/x-msdownload");
				response.setContentLength((int)file.length());
				FileInputStream fin = new FileInputStream(file);
				ServletOutputStream sout = response.getOutputStream();
				byte[] buff = new byte[1024];
				int len = 0;
				while((len=fin.read(buff))!=-1){
					sout.write(buff, 0, len);
					sout.flush();
				}
				fin.close();
				sout.close();
			}
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
